package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.handler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author ryan
 * @since 2021-10-12
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) throws GuliException {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectData.class, new SubjectExcelListener(eduSubjectService))
                    .sheet().doRead();
        }catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20002, "课程分类失败uwu");
        }

    }

    @Override
    public List<OneSubject> getaAllSubject() {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", "0");
        List<EduSubject> eduOneSubjects = baseMapper.selectList(wrapper);
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> eduTwoSubjects = baseMapper.selectList(wrapperTwo);

        ArrayList<OneSubject> allSubject = new ArrayList<>();

        for (int i = 0; i < eduOneSubjects.size(); i++) {
            EduSubject eduOneSubject = eduOneSubjects.get(i);
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduOneSubject, oneSubject);

            ArrayList<TwoSubject> twoSubjects = new ArrayList<>();
            for (int i1 = 0; i1 < eduTwoSubjects.size(); i1++) {
                EduSubject eduTwoSubject = eduTwoSubjects.get(i1);
                if(eduTwoSubject.getParentId().equals(eduOneSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(eduTwoSubject, twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }

            oneSubject.setChildren(twoSubjects);
            allSubject.add(oneSubject);
        }
        return allSubject;
    }
}
